package com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.common.utils.VectorDataUtil;
import com.css.zfzx.sjcj.common.utils.cluster.Bounds;
import com.css.zfzx.sjcj.common.utils.cluster.ObjectTransformerUtil2;
import com.css.zfzx.sjcj.common.utils.cluster.Point;
import com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.repository.QhRiskLevelMapPointProvinceImport;
import com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.repository.QhRiskLevelMapPointProvinceNativeRepository;
import com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.repository.entity.QhRiskLevelMapPointProvinceEntity;
import com.css.zfzx.sjcj.modules.qhrisklevelmappointprovince.viewobjects.QhRiskLevelMapPointQueryParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.*;

/**
 * @author andy
 * @date 2021-01-26
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class QhRiskLevelMapPointProvinceNativeRepositoryImpl implements QhRiskLevelMapPointProvinceNativeRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;

    private static final Logger log = LoggerFactory.getLogger(QhRiskLevelMapPointProvinceNativeRepositoryImpl.class);

    @Override
    public Page<QhRiskLevelMapPointProvinceEntity> queryQhRiskLevelMaps(QhRiskLevelMapPointQueryParams queryParams, int curPage, int pageSize) {
        //zyt--获取省级表名
        String tableName = VectorDataUtil.getSpecialTableNameProvince(queryParams.getProvince(), queryParams.getCity(), queryParams.getArea(), "POINT", true);

        StringBuilder sql = new StringBuilder("select * from " + tableName + " ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        whereSql.append(" and is_valid = '1' ");

        String userId = PlatformSessionUtils.getUserId(), haveAuthorityControl = queryParams.getIsHaveAuthorityControl();;
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if ("1".equals(haveAuthorityControl) && !containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionName");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionName");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and area like :divisionName");
            }
        }

        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), QhRiskLevelMapPointProvinceEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from " + tableName + " ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }

        if ("1".equals(haveAuthorityControl) && !containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                // 根据用户id查询
                query.setParameter("user", userId);
                countQuery.setParameter("user", userId);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionName = ServerUtil.getDivisionEntity().getDivisionName();
                query.setParameter("divisionName", "%" + divisionName + "%");
                countQuery.setParameter("divisionName", "%" + divisionName + "%");
            }
        }

        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<QhRiskLevelMapPointProvinceEntity> list = query.getResultList();

        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<QhRiskLevelMapPointProvinceEntity> qhSiteClassResultPage = new PageImpl<>(list, pageable, count.longValue());
        return qhSiteClassResultPage;
    }

    @Override
    public List<QhRiskLevelMapPointProvinceEntity> listQhRiskLevelMaps(QhRiskLevelMapPointQueryParams queryParams) {
        //zyt--获取省级表名
        String tableName = VectorDataUtil.getSpecialTableNameProvince(queryParams.getProvince(), queryParams.getCity(), queryParams.getArea(), "POINT", true);

        StringBuilder sql = new StringBuilder("select * from " + tableName + " ");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        whereSql.append(" and is_valid = '1' ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getAffiliatedFileName())) {
            whereSql.append(" and affiliated_file_name = :affiliatedFileName");
        }

        String userId = PlatformSessionUtils.getUserId(), haveAuthorityControl = queryParams.getIsHaveAuthorityControl();;
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        // 是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        // 是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        // 是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        // 是否为区级管理员
        boolean containtRoleArea = ServerUtil.isContaintRole(roles, areaCode);

        if ("1".equals(haveAuthorityControl) && !containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user =:user");
            }
            // 省级管理员
            if (containtRolePro) {
                whereSql.append(" and province like :divisionName");
            }
            // 市级管理员
            if (containtRoleCity) {
                whereSql.append(" and city like :divisionName");
            }
            // 区级管理员
            if (containtRoleArea) {
                whereSql.append(" and area like :divisionName");
            }
        }

        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), QhRiskLevelMapPointProvinceEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from " + tableName + " ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getAffiliatedFileName())) {
            query.setParameter("affiliatedFileName", queryParams.getAffiliatedFileName());
            countQuery.setParameter("affiliatedFileName", queryParams.getAffiliatedFileName());
        }

        if ("1".equals(haveAuthorityControl) && !containtRole) {
            // 如果都不是只能查看个人表单
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                // 根据用户id查询
                query.setParameter("user", userId);
                countQuery.setParameter("user", userId);
            }
            // 省级管理员 市级管理员 区级管理员
            if (containtRolePro || containtRoleCity || containtRoleArea) {
                // 获取部门地区名称
                String divisionName = ServerUtil.getDivisionEntity().getDivisionName();
                query.setParameter("divisionName", "%" + divisionName + "%");
                countQuery.setParameter("divisionName", "%" + divisionName + "%");
            }
        }

        List<QhRiskLevelMapPointProvinceEntity> list = query.getResultList();
        return list;
    }

    @Override
    public int lookUpQhRiskLevelMaps(QhRiskLevelMapPointQueryParams queryParams,boolean isNewTable) {
        //zyt--获取省级表名
        String tableName = VectorDataUtil.getSpecialTableNameProvince(queryParams.getProvince(), queryParams.getCity(), queryParams.getArea(), "POINT", isNewTable);

        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        whereSql.append(" and is_valid = '1' ");

        /*StringBuilder countSql = new StringBuilder("select count(*) from " + tableName + " ");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());*/
        //优化查询是否至少有1条数据
        StringBuilder countSql = new StringBuilder("select 1 from " + tableName + " ");
        String sql = countSql.append(whereSql).toString() + " limit 1 ";
        Query countQuery = this.em.createNativeQuery(sql);

        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            countQuery.setParameter("city", queryParams.getCity());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            countQuery.setParameter("area", queryParams.getArea());
        }
        List list = countQuery.getResultList();
        /*Object count = list.get(0);
        return Long.parseLong(count.toString());*/
        int count = 0;
        if(list!=null && list.size()>0){
            count = Integer.parseInt(list.get(0).toString());
        }
        return count;
    }

    @Autowired
    private QhRiskLevelMapPointProvinceImport qhRiskLevelMapPointImport;

    @Override
    public List<QhRiskLevelMapPointProvinceEntity> searchRiskLevelMapsByJDBC(QhRiskLevelMapPointQueryParams queryParams) {
        List<QhRiskLevelMapPointProvinceEntity> list = qhRiskLevelMapPointImport.searchRiskLevelMaps(queryParams, superCode, provinceCode, cityCode, areaCode);
        int zoom = queryParams.getZoom();
        if (zoom >= 15) return list;
        else {
            List<QhRiskLevelMapPointProvinceEntity> result = ObjectTransformerUtil2.getClustersRLMPEntities(list, queryParams.getBounds(), queryParams.getZoom());
            return result;
        }
    }

    @Override
    public Page<QhRiskLevelMapPointProvinceEntity> queryRiskLevelMapsByFileNameJDBC(QhRiskLevelMapPointQueryParams queryParams, int curPage, int pageSize, String sort, String order) {

        Map<String, Date> name2date = new LinkedHashMap<>();
        List<QhRiskLevelMapPointProvinceEntity> list = qhRiskLevelMapPointImport.queryQhRiskLevelMapsByFileName(queryParams, sort, order, superCode, provinceCode, cityCode, areaCode);
        for (int i = 0; i < list.size(); i++) {
            name2date.put(list.get(i).getAffiliatedFileName(), list.get(i).getCreateTime());
        }
        List<QhRiskLevelMapPointProvinceEntity> _list = new ArrayList<>();
        for (Map.Entry<String, Date> entry : name2date.entrySet()) {
            QhRiskLevelMapPointProvinceEntity clmEntity = new QhRiskLevelMapPointProvinceEntity();
            clmEntity.setAffiliatedFileName(entry.getKey());
            clmEntity.setCreateTime(entry.getValue());
            _list.add(clmEntity);
        }

        BigInteger count = BigInteger.valueOf( _list.size());
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);

        Page<QhRiskLevelMapPointProvinceEntity> qhProbabilityEarthquakeDangerPage = new PageImpl<>(_list, pageable, count.longValue());
        return qhProbabilityEarthquakeDangerPage;
    }

    @Override
    public List<String> listQhRiskLevelMapPointsUuidsByJDBC(QhRiskLevelMapPointQueryParams queryParams){
        //zyt-查询文件的全部数据的UUID列表
        List<String> list = qhRiskLevelMapPointImport.listQhRiskLevelMapPointsUuids(queryParams, superCode, provinceCode, cityCode, areaCode);

        return list;
    }
}
